﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Xml.Linq;
using System.IO;
using FR.DataVisualizer;
using System.Windows.Forms;

namespace ConsoleAppTest
{
    class Program
    {
        static string connectionString = @"Data Source=.\sqlexpress;Initial Catalog=M1;Persist Security Info=True;User ID=sa;Password=admin1234;";

        [STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            DataSetTests();
            //LargeDataSetTest();

            //EFTests();
            //LinqTests();
            //EFTestsLoad();

            //CodeTests();

            //SqlConnectionTests();

            //CollectionTests();
            //TestNVarCharMax();
        }

        public class PersonsCategories
        {
            public string Category { get; set; }

            public EFObjectsOC.Person[] PersonList { get; set; }
        }

        private static void TestNVarCharMax()
        {
            using (EFTests.TestsEntities test = new EFTests.TestsEntities())
            {
                string nome = "Lorem";
                var t = from c in test.Table1
                        where c.Name.Contains(nome)
                        select new { c.Name };

                string nomes = "";
                foreach (var item in t)
                {
                    nomes = item.Name;
                }

                string littleName = "a";
                var t2 = from c in test.Table1
                         where c.LittleName.Contains(littleName)
                         select new { c.LittleName };

                foreach (var item in t2)
                {
                    nomes = item.LittleName;
                }


                FR.CodeVisualizer.Visualizers.EFVisualizer.TestShowVisualizer(t);
            }
        }

        private static void CollectionTests()
        {
            using (EFObjectsOC.AdventureWorks2012OCEntities entities = new EFObjectsOC.AdventureWorks2012OCEntities())
            {
                DateTime data = new DateTime(1985, 1, 1);
                var t = from e in entities.Employee
                        where e.BirthDate > data
                        select e;

                List<EFObjectsOC.Employee> lista = t.ToList();
                FR.CodeVisualizer.Visualizers.CollectionVisualizer.TestShowVisualizer(lista);

                Dictionary<string, List<string>> groups = new Dictionary<string, List<string>>();
                groups.Add("A", (new string[] { "Asdsd", "ARGFVE", "Adfds" }).ToList());
                groups.Add("B", (new string[] { "Bsdsd", "BRGFVE", "Bdfds" }).ToList());

                FR.CodeVisualizer.Visualizers.CollectionVisualizer.TestShowVisualizer(groups);
            }
        }

        private static void CodeTests()
        {
            StringBuilder sb = new StringBuilder("uma primeira linha");
            sb.AppendLine("ºewlfºlqfgmrºelmf-.v,nzfvndf-v,nm-.v,mf-cvx.,m");
            sb.AppendLine("çrjepghnrlvghdkj çh fçadsk fçdfan çdsfkndsç");

            FR.CodeVisualizer.SBVisualizer.StringBuilderVisualizer.TestShowVisualizer(sb);

            string xml = "<xml><content attr=\"attribute\">value</content></xml>";

            XDocument doc = XDocument.Parse(xml);
            FR.CodeVisualizer.SBVisualizer.XDocumentVisualizer.TestShowVisualizer(doc);


            string sql = "select * from fact_facturas where Pk_utente is not null";
            FR.CodeVisualizer.SBVisualizer.StringBuilderVisualizer.TestShowVisualizer(sql);
        }

        private static void EFTestsLoad()
        {
            using (MedicineOneEntities entities = new MedicineOneEntities())
            {
                Guid pk = Guid.Parse("156F03D2-C6D6-4097-AC83-0105496D2566");
                var e = from f in entities.FACT_FACTURAS.Include("FACT_DETALHE_FACTURAS")
                        where f.Pk == pk
                        select f;

                var e1 = from f in entities.FACT_FACTURAS
                         where f.Pk == pk
                         select f;

                entities.LoadProperty(e1.FirstOrDefault()
                    , c => c.FACT_DETALHE_FACTURAS
                        .Where(d => d.codigo_acto_clinico == "99050001"));
            }
        }

        private static void EFTests()
        {
            using (EFObjectsOC.AdventureWorks2012OCEntities entities = new EFObjectsOC.AdventureWorks2012OCEntities())
            {
                DateTime data = new DateTime(1980, 1, 1);
                var t = from e in entities.Employee
                        where e.BirthDate > data
                        select e;

                FR.CodeVisualizer.Visualizers.EFVisualizer.TestShowVisualizer(t);
                List<EFObjectsOC.Employee> employees = t.ToList();
                employees.FirstOrDefault().JobTitle = "Up up";
                EFObjectsOC.Employee employeeToDelete = employees.LastOrDefault();
                entities.Employee.DeleteObject(employeeToDelete);

                EFObjectsOC.Employee newEmployee = new EFObjectsOC.Employee();
                newEmployee.HireDate = DateTime.Now;
                newEmployee.Gender = "M";
                newEmployee.JobTitle = "new job";
                newEmployee.NationalIDNumber = "987654321";
                newEmployee.BusinessEntityID = 987654321;

                EFObjectsOC.Employee newEmployee2 = new EFObjectsOC.Employee();
                newEmployee2.HireDate = DateTime.Now;
                newEmployee2.Gender = "M";
                newEmployee2.JobTitle = "new job";
                newEmployee2.NationalIDNumber = "123456789";
                newEmployee2.BusinessEntityID = 123456789;

                entities.AddToEmployee(newEmployee);
                entities.AddToEmployee(newEmployee2);
                FR.CodeVisualizer.Visualizers.EFVisualizer.TestShowVisualizer(entities);
                //int changes = entities.SaveChanges();
            }

            using (EFObjectsOQ.AdventureWorks2012OQEntities entities2 = new EFObjectsOQ.AdventureWorks2012OQEntities())
            {
                DateTime data = new DateTime(1980, 1, 1);
                var t = from e in entities2.Employee
                        where e.BirthDate > data
                        select e;

                FR.CodeVisualizer.Visualizers.EFDbContextVisualizer.TestShowVisualizer(t);

                List<EFObjectsOQ.Employee> employees = t.ToList();
                employees.FirstOrDefault().JobTitle = "Up up";
                EFObjectsOQ.Employee employeeToDelete = employees.LastOrDefault();
                entities2.Employee.Remove(employeeToDelete);

                EFObjectsOQ.Employee newEmployee = new EFObjectsOQ.Employee();
                newEmployee.HireDate = DateTime.Now;
                newEmployee.Gender = "M";
                newEmployee.JobTitle = "new job";
                newEmployee.NationalIDNumber = "987654321";
                newEmployee.BusinessEntityID = 987654321;

                EFObjectsOQ.Employee newEmployee2 = new EFObjectsOQ.Employee();
                newEmployee2.HireDate = DateTime.Now;
                newEmployee2.Gender = "M";
                newEmployee2.JobTitle = "new job";
                newEmployee2.NationalIDNumber = "123456789";
                newEmployee2.BusinessEntityID = 123456789;

                entities2.Employee.Add(newEmployee);
                entities2.Employee.Add(newEmployee2);
                FR.CodeVisualizer.Visualizers.EFDbContextVisualizer.TestShowVisualizer(entities2);

                //int changes = entities2.SaveChanges();
            }
        }

        private static void LinqTests()
        {
            string[] names = new string[] { "one", "two", "three", "four" };

            var t = from n in names
                    where n.StartsWith("t")
                    select n;

        }

        private static void DataSetTests()
        {
            //teste 1
            //DataSet ds = devolveDataSetPorSql("select * from fact_facturas");
            //ds.Tables.Add(devolveDataTablePorSql("select * from fact_detalhe_facturas", "fact_detalhe_facturas"));

            //DataSetVisualizer.DSVisualizer.TestShowVisualizer(ds);


            //teste 2
            DataSetTestTableAdapters.FACT_FACTURASTableAdapter taF = new DataSetTestTableAdapters.FACT_FACTURASTableAdapter();
            DataSetTestTableAdapters.FACT_DETALHE_FACTURASTableAdapter taD = new DataSetTestTableAdapters.FACT_DETALHE_FACTURASTableAdapter();
            DataSetTestTableAdapters.FACT_DETALHE_FACTURAS_AUXILIARTableAdapter taDA = new DataSetTestTableAdapters.FACT_DETALHE_FACTURAS_AUXILIARTableAdapter();

            DataSetTest dsTest = new DataSetTest();
            Guid pkFactura = Guid.Parse("EC04D005-67CD-4B50-98C1-004844DF2BB5");
            taF.FillByPk(dsTest.FACT_FACTURAS, pkFactura);
            taD.FillByPkFactura(dsTest.FACT_DETALHE_FACTURAS, pkFactura);
            taDA.FillByPkFactura(dsTest.FACT_DETALHE_FACTURAS_AUXILIAR, pkFactura);

            dsTest.FACT_DETALHE_FACTURAS.Rows.RemoveAt(0);

            //FR.DataVisualizer.DSVisualizer.TestShowVisualizer(dsTest);

            //teste 3
            DataTable dt = dsTest.FACT_DETALHE_FACTURAS;
            //FR.DataVisualizer.DTVisualizer.TestShowVisualizer(dt);

            var temp = new DataTable();

            //teste 4
            DataRow dr = dsTest.FACT_DETALHE_FACTURAS.Rows[0];
            FR.DataVisualizer.DRVisualizer.TestShowVisualizer(dr);

            //teste 5
            DataView dv = dsTest.FACT_DETALHE_FACTURAS.AsDataView();
            FR.DataVisualizer.DVVisualizer.TestShowVisualizer(dv);

            //teste 6
            dv.Sort = "Pk";
            DataRowView drv = dv.FindRows(pkFactura)[0];
            FR.DataVisualizer.DRVVisualizer.TestShowVisualizer(drv);

            //teste 7
            DataRowCollection drc = dt.Rows;
            FR.DataVisualizer.DRCollectionVisualizer.TestShowVisualizer(drc);
        }

        private static void LargeDataSetTest()
        {
            DataSet ds = new DataSet();
            ds.Tables.Add();

            //add columns
            int i = 0;
            for (; i < 10; i++)
            {
                ds.Tables[0].Columns.Add(i.ToString(), typeof(int));
            }
            for (; i < 10 * 2; i++)
            {
                ds.Tables[0].Columns.Add(i.ToString(), typeof(string));
            }
            for (; i < 10 * 3; i++)
            {
                ds.Tables[0].Columns.Add(i.ToString(), typeof(decimal));
            }

            //add rows
            Random r = new Random();
            for (int j = 0; j < 1000; j++)
            {
                List<object> row = new List<object>();

                foreach (DataColumn column in ds.Tables[0].Columns)
                {
                    if (column.DataType == typeof(int))
                    {
                        row.Add((int)(r.NextDouble() * 1000));
                    }
                    else if (column.DataType == typeof(string))
                    {
                        row.Add(Path.GetRandomFileName());
                    }
                    else if (column.DataType == typeof(decimal))
                    {
                        row.Add((decimal)(r.NextDouble() * 1000));
                    }
                }

                ds.Tables[0].Rows.Add(row.ToArray());
            }
            ds.Tables[0].Rows[0].SetColumnError(5, "Muito grave");

            DSVisualizer.TestShowVisualizer(ds);
        }

        private static void SqlConnectionTests()
        {
            connectionString = @"Data Source=.\sqlexpress;Initial Catalog=AdventureWorks2012;Persist Security Info=True;User ID=sa;Password=admin1234;";
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                string queryString = "SELECT * FROM HumanResources.Employee WHERE BirthDate >= @birth_date";
                SqlCommand command = new SqlCommand(queryString, connection);
                command.Parameters.Add("@birth_date", SqlDbType.DateTime);
                command.Parameters["@birth_date"].Value = new DateTime(1980, 01, 01);

                try
                {
                    connection.Open();
                    Int32 rowsAffected = command.ExecuteNonQuery();
                    Console.WriteLine("RowsAffected: {0}", rowsAffected);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                FR.CodeVisualizer.Visualizers.SqlCommandVisualizer.TestShowVisualizer(command);
            }
        }

        private static DataSet devolveDataSetPorSql(string sql)
        {
            DataSet x = new DataSet();
            SqlConnection conn = null;

            try
            {
                DateTime ini = DateTime.Now;
                conn = new SqlConnection(connectionString);
                conn.Open();
                SqlDataAdapter sad = new SqlDataAdapter(sql, conn);
                sad.Fill(x);

                if (conn.State != ConnectionState.Closed)
                {
                    conn.Close();
                    conn.Dispose();
                }

                sad.Dispose();
                conn.Dispose();

                return x;
            }
            catch
            {
                if (conn != null && conn.State != ConnectionState.Closed)
                {
                    conn.Close();
                    conn.Dispose();
                }
                return null;
            }
        }

        private static DataTable devolveDataTablePorSql(string sql, string tableName = "Table1")
        {
            DataTable dt = new DataTable(tableName);
            SqlConnection conn = null;

            try
            {
                DateTime ini = DateTime.Now;
                conn = new SqlConnection(connectionString);
                conn.Open();
                SqlDataAdapter sad = new SqlDataAdapter(sql, conn);
                sad.Fill(dt);

                if (conn.State != ConnectionState.Closed)
                {
                    sad.Dispose();
                    conn.Close();
                    conn.Dispose();
                }

                return dt;
            }
            catch
            {
                if (conn != null && conn.State != ConnectionState.Closed)
                {
                    conn.Close();
                    conn.Dispose();
                }
                return null;
            }
        }
    }
}
